package com.feihong.yw189.paidan.qiangdanservice.newversion;


import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.feihong.yw189.R;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.utils.util.ConstantsValue;
import com.feihong.yw189.bluetooth.utils.util.PrefUtils;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.paidan.activity.DispatchActivity;
import com.feihong.yw189.paidan.bean.PaiDanServiceInfo;
import com.feihong.yw189.paidan.qiangdanservice.LocationCallBack;
import com.feihong.yw189.paidan.qiangdanservice.LocationInfo;
import com.feihong.yw189.paidan.qiangdanservice.LocationTools;
import com.feihong.yw189.paidan.qiangdanservice.notification.BaseBuilder;
import com.feihong.yw189.paidan.qiangdanservice.notification.NotifyUtil;
import com.feihong.yw189.paidan.tools.RefReshToken;
import com.google.gson.Gson;

import org.xutils.common.Callback;

/**
 * Created by Sabirjan
 */

public class PaiDanRemoteService extends Service implements MediaPlayer.OnCompletionListener {

    public static final String LAST_LOC_TIME = "PaiDanLocationLastTime";
    public static final String PaiDanLongitude = "PaiDanLongitude";
    public static final String PaiDanLatitude = "PaiDanLatitude";


    private final int RES_ID = R.raw.xinxiaoxi;
    private static final int NOT_ID = 20015;
    private static final int NOT_ID2 = 20016;
    private static final String TAG = "派单";
    private boolean isFirst = true;
    public LocationTools locationTools;
    private int count = 0;
    public boolean isRunning = false;
    private MediaPlayer mediaPlayer;
    private boolean isPlayningNewOrder = false;

    private void initLocationTools() {
        try {
            if (locationTools != null) {
                locationTools.stopLocation();
                locationTools = null;
            }
            NotifyUtil.init(this);
            NotifyUtil.cancel(NOT_ID);

        } catch (Exception ex) {
        }
        isRunning = false;
        locationTools = new LocationTools(this, mLocationCallBack);

    }

    private LocationCallBack mLocationCallBack = new LocationCallBack() {

        @Override
        public void successGetLocation(LocationInfo info) {

            Log.e(TAG, "------successGetLocation------" + info.toString());
            if (!PrefUtils.getBoolean(PaiDanRemoteService.this, ConstantsValue.PAIDAN_STATE, false)) {
                if (locationTools != null) {
                    locationTools.stopLocation();
                    isRunning = false;
                    locationTools = null;
                    NotifyUtil.init(PaiDanRemoteService.this);
                    NotifyUtil.cancelAll();
                    return;
                }

            }
            if (info != null) {

                String Latitude = info.getLatitude() + "";
                String Longitude = info.getLongitude() + "";
                if (TextUtils.isEmpty(Latitude) || TextUtils.isEmpty(Longitude)) {
                    return;
                }
                sendLocation(Latitude, Longitude);
                ///    Toast.makeText(getApplicationContext(), "获取中..." + count, Toast.LENGTH_SHORT).show();
                count++;
                //发送通知
                //  EventBus.getDefault().postSticky(new PaiDanRefreshEvent());
                Log.i(TAG, "发送消息了.........");
                showNitification();
                Log.d(TAG, "successGetLocation() called with: info = [" + info + "]");
            }


        }

        @Override
        public void error(String error) {
            Log.d(TAG, "error() called with: error = [" + error + "]");
        }

        private void refreshToken() {
            if (locationTools != null) {
                locationTools.stopLocation();
            }
            // 刷新Token
            Boolean sucRef = RefReshToken.refshToken();
            if (sucRef) {
                initLocationTools();
                locationTools.startLocation(0);
            } else {
                RefReshToken.exitLogin();
            }
        }

        private void sendLocation(String Latitude, String Longitude) {
            if (isPlayningNewOrder) return;

            App.getApp().getHttpTools().getPaiDan("location", Latitude, Longitude, new RequestCallBack<String>() {
                @Override
                public void onSuccess(String s) {
                    Log.i(TAG, "sendLocation--onSuccess: S=" + s);
                    try {
                        Gson gson = new Gson();
                        PaiDanServiceInfo paiDanServiceInfo = gson.fromJson(s, PaiDanServiceInfo.class);
                        if (paiDanServiceInfo == null) {
                            refreshToken();
                            return;
                        }
                        int status = paiDanServiceInfo.getStatus();
                        if (status == 401) {
                            //token过期刷新
                            refreshToken();
                            return;
                        }

                        if (status == 1) {
                            int data = paiDanServiceInfo.getData().getData();
                            if (data > 0) {
                                showNitification(data + "");
                            }
                        }

                    } catch (Exception e) {
                        Log.e(TAG, "Exception: S=" + e.toString());
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Log.e(TAG, "------err------" + "网络错误:" + ex);
                }

                @Override
                public void onCancelled(Callback.CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        }
    };


    private void showNitification(String count) {

        if (isPlayningNewOrder) return;
        isPlayningNewOrder = true;
        if (locationTools != null) {
            locationTools.stopLocation();
            locationTools = null;
        }
        NotifyUtil.init(this);
        NotifyUtil.cancel(NOT_ID2);
        BaseBuilder builder = NotifyUtil.buildSimple(NOT_ID2, R.mipmap.icon, "营维189-新订单提示", "有新的订单了，点击进行处理,未处理订单数量:" + count, NotifyUtil.buildIntent(DispatchActivity.class))
                .setHeadup();
        builder = builder.setAction(false, true, true);
        builder = builder.setSmallIcon(R.mipmap.icon);
        builder.setTicker("发现新的订单了");
        builder.show();
        play();


    }

    private void play() {
        try {
            mediaPlayer = MediaPlayer.create(this, RES_ID);//重新设置要播放的音频
            mediaPlayer.setOnCompletionListener(this);

        } catch (Exception e) {
            e.printStackTrace();//输出异常信息
        }
        mediaPlayer.start();//开始播放
    }

    private void showNitification() {
        NotifyUtil.init(this);
        // NotifyUtil.cancel(NOT_ID);

        BaseBuilder builder = NotifyUtil.buildSimple(NOT_ID, R.mipmap.icon, "营维189", "正在接单中...", NotifyUtil.buildIntent(DispatchActivity.class))
                .setHeadup();
        builder = builder.setAction(false, false, true);
        builder = builder.setSmallIcon(R.mipmap.icon);
        builder.setOnGoing();
        builder.autoClean = false;
        builder.setTicker("正在接单中...");
        builder.show();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {

        initLocationTools();
        locationTools.startLocation(10000);
        if (mediaPlayer != null) {
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        isPlayningNewOrder = false;

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("派单", "PaiDanRemoteService is on receive: " + GlobalController.isRuning);
        if (PrefUtils.getBoolean(this, ConstantsValue.PAIDAN_STATE, false)) {
            if (!isRunning || locationTools == null) {
                initLocationTools();
                locationTools.startLocation(0);
                showNitification();
                isRunning = true;
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                Notification.Builder builder = new Notification.Builder(this);
                builder.setSmallIcon(R.mipmap.icon);
                startForeground(111, builder.build());
            } else {
                startForeground(111, new Notification());
            }
            startService(new Intent(this, DaemonService.class));

            return START_STICKY;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        if (locationTools != null) {
            locationTools.stopLocation();
        }
        isRunning = false;
        locationTools = null;
        NotifyUtil.init(PaiDanRemoteService.this);
        NotifyUtil.cancelAll();
        Log.i("派单", "PaiDanRemoteService is Destroy");
        super.onDestroy();
    }
}